package org.example.consumer.queue;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @description: 消费者
 */
public class ConsumerTest2 {

    //队列名称
    public static final String QUEUE_HELLOWORD = "helloworld";

    /**
     * 步骤：
     * 1、创建连接
     * 2、创建信道
     * 3、监听队列
     * 4、处理消息
     */
    public static void main(String[] args) throws Exception {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost("localhost");
        //1、创建连接，通过工厂获取连接
        Connection connection = factory.newConnection();
        //2、创建信道
        Channel channel = connection.createChannel();
        //todo 设置并发处理数量：1
        channel.basicQos(1);
        //3、监听队列(接收消息)
        channel.basicConsume(QUEUE_HELLOWORD, false, new DefaultConsumer(channel){
            //4、处理消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("我是消费者Consumer2，收到消息：" + new String(body));
//                //消费者标签
//                System.out.println("consumerTag=" + consumerTag);
//                //交换机
//                System.out.println("getExchange=" + envelope.getExchange());
//                //路由key
//                System.out.println("getRoutingKey=" + envelope.getRoutingKey());
//                //消息ID
//                System.out.println("getDeliveryTag=" + envelope.getDeliveryTag());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}